package com.ruoyi.job.task;

import com.ruoyi.common.core.constant.ScheduleConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.job.domain.EtlScriptTask;
import com.ruoyi.job.domain.EtlTaskInst;
import com.ruoyi.job.domain.EtlTaskState;
import com.ruoyi.job.domain.SysJob;
import com.ruoyi.job.kettle.KettleQuartz;
import com.ruoyi.job.mapper.EtlScriptTaskMapper;
import com.ruoyi.job.mapper.EtlTaskInstMapper;
import com.ruoyi.job.mapper.EtlTaskStateMapper;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerMetaData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 初始化所有的kettle调度任务
 */
//@Component("etlSchedTask")
public class EtlSchedTask {
    private Logger logger = LoggerFactory.getLogger(EtlSchedTask.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private EtlTaskInstMapper etlTaskInstMapper;

    @Autowired
    private EtlScriptTaskMapper etlScriptTaskMapper;

    @Autowired
    private EtlTaskStateMapper etlTaskStateMapper;


    public void initWithParams(String taskName) {
        /**
         * 如果选择“执行一次”，则前端必须传递执行日期
         */
        String exeDate = "";
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        exeDate=sdf.format(calendar.getTime());

        SysJob job = new SysJob();
        String errorMsg = "";

        /**
         * 找到当前执行任务的参数job
         */
        try{
            String instanceId =  scheduler.getSchedulerInstanceId();
            List<JobExecutionContext> contextList  = scheduler.getCurrentlyExecutingJobs();

            for(JobExecutionContext context:contextList){
                String tmpId = context.getScheduler().getSchedulerInstanceId();
                if(instanceId.equals(tmpId)){
                    job = (SysJob) context.getJobDetail().getJobDataMap().get(ScheduleConstants.TASK_PROPERTIES);
                    break;
                }
            }

        } catch (Exception e){
            errorMsg = e.getMessage();
        }

        if(job == null) {
            errorMsg = "未找到任务信息,任务名称==>" + taskName;
        }

        //保存任务实例表
        EtlTaskInst inst=new EtlTaskInst();
        inst.setTaskId(job.getJobId());
        inst.setLogType(1);//自动方式
        inst.setFlag(0);//未处理
        inst.setScriptId(job.getScriptId());
        inst.setExeTime(DateUtils.getNowDate());
        inst.setTaskDate(exeDate);
        inst.setManualFlag(0);
        etlTaskInstMapper.insertEtlTaskInst(inst);

        //保存脚本执行任务表
        EtlScriptTask scriptTask=new EtlScriptTask();
        scriptTask.setInstId(inst.getInstId());
        scriptTask.setScriptId(job.getScriptId());
        scriptTask.setCreateTime(new Date());
        scriptTask.setStatus(0);//待处理
        scriptTask.setTaskId(job.getJobId());
        scriptTask.setTaskDate(exeDate);
        scriptTask.setParamPk(1);
        etlScriptTaskMapper.insertEtlScriptTask(scriptTask);

        List<EtlTaskState> list=etlTaskStateMapper.getSriptTask(job.getJobId(),exeDate);
        if(list != null && list.size()>0){
            EtlTaskState old = list.get(0);
            etlTaskStateMapper.updateEtlScriptTaskBySql(old.getTaskId(),old.getTaskDate());
        }else{
            EtlTaskState state=new EtlTaskState();
            state.setTaskId(job.getJobId());
            state.setScriptId(job.getScriptId());
            state.setState(0);
            state.setTaskDate(exeDate);
            state.setTaskName(job.getJobName());
            etlTaskStateMapper.insertEtlTaskState(state);
        }
    }
}
